package com.taotao.tools.mybatis.plugins.sass.tenantid;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.util.JdbcConstants;
import com.taotao.tools.mybatis.plugins.sass.AbstractSassInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author youbeiwuhuan
 * @version 1.0.0
 * @date 2022/12/23 15:28
 */
@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),})
public class TenantIdColumIntercepter extends AbstractSassInterceptor {

    private String tenantIdColumnName;

    /**
     * @param ignoreTables 忽略的表,多个表用逗号隔开
     */
    public TenantIdColumIntercepter(String ignoreTables, String tenantIdColumnName) {
        super(ignoreTables);
        this.tenantIdColumnName = tenantIdColumnName;
    }

    @Override
    protected String reWriteSql(String sql, String tenantId) {
        String dbType = JdbcConstants.MYSQL;
        List<SQLStatement> statementList = SQLUtils.parseStatements(sql, dbType);
        SQLStatement sqlStatement = statementList.get(0);
        //决策器定义
        SqlConditionHelper helper = new SqlConditionHelper(new ITableFieldConditionDecision() {
            @Override
            public boolean adjudge(String tableName, String fieldName, String fieldValue) {

                if (IGNORE_TABLES.contains(tableName)) {
                    return false;
                }

                return true;
            }

        });
        //添加多租户条件，domain是字段ignc，yay是筛选值
        helper.addStatementCondition(sqlStatement, tenantIdColumnName, tenantId);
        log.debug("源sql：{}", sql);
        log.debug("修改后sql{}", SQLUtils.toSQLString(statementList, dbType));
        return SQLUtils.toSQLString(statementList, dbType);
    }
}
